package com.shycloud.mido.music.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.music.domain.MisMusic;
import com.shycloud.mido.music.dto.CheckUploadResultDTO;
import com.shycloud.mido.music.mapper.MisMusicMapper;
import com.shycloud.mido.music.service.MisMusiOssService;
import com.shycloud.mido.music.service.MisMusicService;
import com.shycloud.mido.music.service.MisMusicUploadService;
import com.shycloud.mido.music.util.CommonString;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 上传曲谱业务
 *
 * @author nianhua.jiang
 * @date 2020/8/4
 */
@AllArgsConstructor
@Service
public class MisMusiOssServiceImpl implements MisMusiOssService {

	private static Log logger = LogFactory.getLog(MisMusiOssServiceImpl.class);

	/** 曲目模块 service */
	private final MisMusicService musicService;
	/** 曲目模块 mapper */
	private final MisMusicMapper musicMapper;

	/** 七牛云 OSS */
	private final MinioTemplate minioTemplate;

	/** 上传服务 **/
	private final MisMusicUploadService misMusicUploadService;

	private RedisTemplate redisTemplate;

	/** 错误信息：请先选择所属曲集 */
	private static final String MSG_CHOOSE_COLLECTION = "请先选择所属曲集";
	/** 错误信息：请先选择所属曲集 */
	private static final String OPERATE_ERROR = "上传操作失败，请重新尝试";
	/** 错误信息：缺少xml和svg文件 */
	private static final String MSG_LOCK_XML_SVG = "缺少xml和svg文件";
	/** 错误信息：缺少svg文件 */
	private static final String MSG_LACK_SVG = "缺少svg文件";
	/** 错误信息：缺少xml文件 */
	private static final String MSG_LACK_XML = "缺少xml文件";
	/** 错误信息：文件名不匹配 */
	private static final String MSG_FILE_NAME_NOT_MATCH = "文件名不匹配";
	/** 错误信息：请先上传曲目资源 */
	private static final String MSG_UPLOAD_MUSIC_FILE = "请先上传曲目资源";
	/** 错误信息：只能上传一首伴奏资源 */
	private static final String MSG_ONLY_ONE_KALA = "只能上传一首伴奏资源";
	/** 错误信息：请上传mp3文件 */
	private static final String MSG_UPLOAD_MP3_FILE = "请上传mp3文件";
	/** 错误信息：一共只能上传两个文件 */
	private static final String MSG_UPLOAD_ONLY_TWO = "一共只能上传两个文件";
	/** 错误信息：文件格式错误，请确认 */
	private static final String MSG_FILE_TYPE_ERROR = "文件格式错误，请确认";
	/** 错误信息：缺少文件 */
	private static final String MSG_LACK_FILE = "缺少文件";
	/** 错误信息：请上传常用格式的视频文件 */
	private static final String MSG_UPLOAD_MV_FILE = "请上传常用格式的视频文件";
	/** 错误信息：曲目资源不存在 */
	private static final String MSG_NON_MUSIC_FILE = "曲目资源不存在，请重新上传";
	/** 错误信息：部分伴奏不存在于该曲集下，请重新上传 */
	//public static final String MSG_KALA_NOT_IN_COLLECTION = "部分伴奏不存在于该曲集下，请重新上传";
	/** 错误信息：部分音频不存在于该曲集下，请重新上传 */
	//public static final String MSG_MUSIC_NOT_IN_COLLECTION = "部分音频不存在于该曲集下，请重新上传";
	/** 错误信息：部分视频不存在于该曲集下，请重新上传 */
	//public static final String MSG_MV_NOT_IN_COLLECTION = "部分视频不存在于该曲集下，请重新上传";
	/** 错误信息：只可以上传 svg 和 xml 文件 */
	private static final String MSG_ONLY_UPLOAD_SVG_XML = "只可以上传 svg 和 xml 文件";
	/** 伴奏的 bucket */
	private static final String BUCKET_KALA = "mido-music-file";
	/** 音视频资源的 bucket */
	private static final String BUCKET_MP3_MV = "mido-music-file";
	/** 带解析文件的 bucket */
	private static final String BUCKET_SOURCE_FILE = "mido-songbook-sourcefile";

	/** 后缀名 ：svg */
	private static final String SUFFIX_SVG = "svg";
	/** 后缀名 ：xml */
	private static final String SUFFIX_XML = "xml";
	/** 后缀名 ：MP3 */
	private static final String SUFFIX_MP3 = "mp3";
	/** 后缀名: JPEG */
	private static final String SUFFIX_JPEG = "JPEG";
	/** 后缀名: JPG */
	private static final String SUFFIX_JPG = "JPG";
	/** 后缀名: PNG */
	private static final String SUFFIX_PNG = "PNG";

	/** 视频资源的编码格式 */
	private static final String[] mvFileType = {"Mp4", "mP4", "MP4", "mp4", "avi", "AVI", "wmv", "mpeg", "mov", "3gp"};

	/**
	 * 上传曲目资源文件
	 *
	 * @param files        曲目文件
	 * @param collectionId 曲集ID
	 * @param musicId      曲目ID（新增/更新判断依据）
	 * @return musicId     曲目ID
	 * @author nianhua.jiang
	 * @date 2020/8/4 14:19
	 */
	@Override
	public Integer uploadMusicFile(List<MultipartFile> files, Integer collectionId, Integer musicId) {

		//曲集ID为空
		if (collectionId == null) {
			throw new BusinessException(MSG_CHOOSE_COLLECTION);
		}

		//定义map检索集
		Map<String, Integer> map = MapUtil.newHashMap();

		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", CommonString.EMPTY);
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);

			//== 2020/10/07 追加判断不允许其他格式文件上传 ===============================//
			if (!SUFFIX_SVG.equals(fileSuffix) && !SUFFIX_XML.equals(fileSuffix)) {
				throw new BusinessException(MSG_ONLY_UPLOAD_SVG_XML);
			}
			//== 2020/10/07 ========================================================//

			if (SUFFIX_SVG.equals(fileSuffix)) {
				map.put(SUFFIX_SVG, 1);
				continue;
			}
			if (SUFFIX_XML.equals(fileSuffix)) {
				map.put(SUFFIX_XML, 1);
			}
		}

		if (map.get(SUFFIX_SVG) == null && map.get(SUFFIX_XML) == null) {
			throw new BusinessException(MSG_LOCK_XML_SVG);
		}

		if (map.get(SUFFIX_SVG) == null) {
			throw new BusinessException(MSG_LACK_SVG);
		}

		if (map.get(SUFFIX_XML) == null) {
			throw new BusinessException(MSG_LACK_XML);
		}

		//校验文件名
		String fileNameResult = checkFileName(files);

		if (StringUtils.EMPTY.equals(fileNameResult)) {
			throw new BusinessException(MSG_FILE_NAME_NOT_MATCH);
		}


		//==========  文件完整,开始上传 START===============//

		if (musicId != null) {

			MisMusic music = musicService.getById(musicId);

			int i = 1;
			for (MultipartFile file : files) {
				try {
					//提取文件后缀
					String fileName = file.getOriginalFilename().replace(" ", "");
					String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

					String ossFileName = "";

					if (SUFFIX_XML.equals(suffix)) {
						ossFileName = collectionId + "/" + musicId + "/" + musicId + "." + suffix;
					} else {
						ossFileName = collectionId + "/" + musicId + "/" + musicId + "_" + i + "." + suffix;
						i++;
					}

					//上传操作
					minioTemplate.uploadFile(file.getInputStream(), ossFileName, BUCKET_SOURCE_FILE);
				} catch (Exception e) {
					throw new BusinessException(e.getLocalizedMessage());
				}
			}

			//OSS 文件路径
			music.setOssFile(collectionId + "/" + music.getId() + "/");
			//修改状态改为未解析
			music.setFileStatus("0");

			musicService.updateById(music);
		}

		//新增
		else {
			//首先插入 曲目表一条信息，返回 music_id 作为文件名进行上传
			MisMusic music = new MisMusic();
			//所属曲集
			music.setCollectionId(collectionId);
			//创建时间
			music.setCreateTime(new Date());
			//曲目名称
			music.setName(fileNameResult);
			//新增
			musicService.save(music);
			musicId = music.getId();
			int i = 1;
			for (MultipartFile file : files) {
				try {

					//提取文件后缀
					String fileName = file.getOriginalFilename().replace(" ", "");
					String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

					String ossFileName = "";

					if (SUFFIX_XML.equals(suffix)) {
						ossFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "." + suffix;
					} else {
						ossFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "_" + i + "." + suffix;
						i++;
					}

					//上传操作
					minioTemplate.uploadFile(file.getInputStream(), ossFileName, BUCKET_SOURCE_FILE);

				} catch (Exception e) {
					throw new BusinessException(e.getLocalizedMessage());
				}
			}

			//上传成功，更新music的oss_file名 最后的 "/" 一定要留，否则会导致解析失败，删除请确认。
			music.setOssFile(collectionId + "/" + music.getId() + "/");

			musicService.updateById(music);
		}
		//返回曲目ID
		return musicId;
	}

	/**
	 * 上传伴奏资源
	 *
	 * @param files
	 * @param collectionId
	 * @param musicId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:17
	 */
	@Override
	public Boolean uploadKala(List<MultipartFile> files, Integer collectionId, Integer musicId) {

		//曲目ID为空，则曲目资源为空，无此曲目
		if (musicId == null) {
			throw new BusinessException(MSG_UPLOAD_MUSIC_FILE);
		}

		if (collectionId == null) {
			throw new BusinessException(MSG_CHOOSE_COLLECTION);
		}

		if (files != null && files.size() > 1) {
			throw new BusinessException(MSG_ONLY_ONE_KALA);
		}

		//获取曲目信息
		MisMusic music = musicService.getById(musicId);

		if (files.size() == 1) {
			//提取文件名
			String fileName = files.get(0).getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);

			if (!SUFFIX_MP3.equals(fileSuffix) && !"wav".equals(fileSuffix)) {
				throw new BusinessException(MSG_UPLOAD_MP3_FILE);
			}

			String ossKalaFileName = collectionId + "/" + musicId + "/" + musicId + "_kala." + fileSuffix;

			try {
				// 上传文件
				minioTemplate.uploadFile(files.get(0).getInputStream(), ossKalaFileName, BUCKET_KALA);
				//更新伴奏状态
				music.setKalaFile(CommonString.OSS_MUSIC_FILE + ossKalaFileName);
				music.setKalaStatus("1");

				return musicService.updateById(music);

			} catch (IOException e) {
				throw new BusinessException(e.getLocalizedMessage());
			}
		}

		//若传入文件为空，则代表删除伴奏
		if (files.size() == 0) {
			//更新伴奏文件为 null
			music.setKalaFile(null);
			//更新伴奏状态为 无
			music.setKalaStatus("0");

			return musicMapper.clearKalaFile(music.getId()) == 1;
		}
		return false;
	}

	/**
	 * 上传音视资源
	 *
	 * @param files
	 * @param collectionId
	 * @param musicId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:34
	 */
	@Override
	public Boolean uploadMp3AndMV(List<MultipartFile> files, Integer collectionId, Integer musicId) {

		if (musicId == null) {
			throw new BusinessException(MSG_UPLOAD_MUSIC_FILE);
		}

		if (collectionId == null) {
			throw new BusinessException(MSG_CHOOSE_COLLECTION);
		}

		//TODO 删除的逻辑
		//处理删除的操作逻辑
//		if (files == null || files.size() == 0) {
//			try {
//				MisMusic misMusic = musicService.getById(musicId);
//
//				String ossMp3FileName = null;
//
//				if (fileType.equals("mp3")) {
//					//获取后缀名
//					String fileSuffix = "mp3";
//					//拼接七牛key
//					ossMp3FileName = collectionId + "/" + musicId + "/" + musicId + "_mp3." + fileSuffix;
//				} else if (fileType.equals("mp4")) {
//					//获取后缀名
//					String fileSuffix = "mp3";
//					//拼接七牛key
//					ossMp3FileName = collectionId + "/" + musicId + "/" + musicId + "_mp3." + fileSuffix;
//				}
//
//				minioTemplate.delete(ossMp3FileName);
//			} catch (QiniuException e){
//				throw new BusinessException(OPERATE_ERROR);
//			}
//		}

		if (files.size() > 2) {
			throw new BusinessException(MSG_UPLOAD_ONLY_TWO);
		}

		MisMusic misMusic = musicService.getById(musicId);

		misMusic.setMp3File(null);

		misMusic.setMvFile(null);

		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);

			if (SUFFIX_MP3.equals(fileSuffix)) {
				//开始上传MP3文件
				String ossMp3FileName = collectionId + "/" + musicId + "/" + musicId + "_mp3." + fileSuffix;
				try {
					//获取上传路径
					String url = minioTemplate.uploadFile(file.getInputStream(), ossMp3FileName, "mido-music-file");
					//更新mp3文件
					misMusic.setMp3File(CommonString.OSS_MUSIC_FILE + ossMp3FileName);
				} catch (IOException e) {
					throw new BusinessException(e.getLocalizedMessage());
				}
			}

			//mv文件
			if (Arrays.asList(mvFileType).contains(fileSuffix)) {

				//开始上传MV文件
				String ossMVFileName = collectionId + "/" + musicId + "/" + musicId + "_mv." + fileSuffix;
				try {
					//获取上传路径
					String url = minioTemplate.uploadFile(file.getInputStream(), ossMVFileName, BUCKET_MP3_MV);
					//更新mv文件
					misMusic.setMvFile(CommonString.OSS_MUSIC_FILE + ossMVFileName);
				} catch (IOException e) {
					throw new BusinessException(e.getLocalizedMessage());
				}
			}
		}
		return musicService.updateById(misMusic);
	}

	/**
	 * 批量上传曲目
	 *
	 * @param files
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:42
	 */
	@Override
	public Boolean uploadBatchMusic(List<MultipartFile> files, Integer collectionId) {

		Map<String, List<MultipartFile>> fileNameMap = MapUtil.newHashMap();

		//循环批量文件，按照名称进行分组
		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);

			String filedNameBefore = StringUtils.EMPTY;

			//xml 文件
			if (SUFFIX_XML.equals(fileSuffix)) {
				//提取文件名（不含后缀）
				filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));
			} else if (SUFFIX_SVG.equals(fileSuffix)) {
				//提取文件名（不含后缀）
				filedNameBefore = fileName.substring(0, fileName.lastIndexOf(".") - 3);
			} else {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_FILE_TYPE_ERROR);
			}

			List<MultipartFile> filesResult = fileNameMap.get(filedNameBefore);

			if (filesResult == null) {
				filesResult = new ArrayList<>();
			}
			filesResult.add(file);
			fileNameMap.put(filedNameBefore, filesResult);
		}

		//循环分组 map
		for (String key : fileNameMap.keySet()) {
			//获取相同文件集合
			List<MultipartFile> fileNameList = fileNameMap.get(key);

			Map<String, Integer> checkMap = MapUtil.newHashMap();

			//遍历文件集合，开始判断文件后缀是否缺少
			for (MultipartFile file : fileNameList) {

				//提取文件名
				String fileName = file.getOriginalFilename().replace(" ", "");
				//获取后缀名
				String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);

				if (!SUFFIX_SVG.equals(fileSuffix) && !SUFFIX_XML.equals(fileSuffix)) {
					throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_FILE_TYPE_ERROR);
				}

				if (SUFFIX_SVG.equals(fileSuffix)) {
					checkMap.put(SUFFIX_SVG, 1);
					continue;
				}

				if (SUFFIX_XML.equals(fileSuffix)) {
					checkMap.put(SUFFIX_XML, 1);
				}

			}

			if (checkMap.get(SUFFIX_SVG) == null && checkMap.get(SUFFIX_XML) == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_LACK_FILE);
			}

			if (checkMap.get(SUFFIX_SVG) == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_LACK_FILE);
			}

			if (checkMap.get(SUFFIX_SVG) == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_LACK_FILE);
			}

			//首先清除文件名相同的曲目
			musicService.remove(new QueryWrapper<MisMusic>().eq(MisMusic.COL_NAME, key));

			//首先插入 曲目表一条信息，返回 music_id 作为文件名进行上传
			MisMusic music = new MisMusic();
			//所属曲集
			music.setCollectionId(collectionId);
			//创建时间
			music.setCreateTime(new Date());
			//曲目名称
			music.setName(key);
			//新增
			musicService.save(music);

			int i = 1;

			for (MultipartFile file : fileNameList) {

				try {
					//提取文件后缀
					String fileName = file.getOriginalFilename().replace(" ", "");
					String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

					String ossFileName = "";

					if (SUFFIX_XML.equals(suffix)) {
						ossFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "." + suffix;
						//上传操作
						minioTemplate.uploadFile(file.getInputStream(), ossFileName, BUCKET_SOURCE_FILE);
						continue;
					}

					if (SUFFIX_SVG.equals(suffix)) {
						ossFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "_" + i + "." + suffix;
						i++;
						//上传操作
						minioTemplate.uploadFile(file.getInputStream(), ossFileName, BUCKET_SOURCE_FILE);
						continue;
					}

				} catch (Exception e) {
					throw new BusinessException(CommonConstants.FAIL_BOARD, e.getLocalizedMessage());
				}

			}

			//上传成功，更新music的 oss_file名 最后的 "/" 一定要留，否则会导致解析失败，删除请确认。
			music.setOssFile(collectionId + "/" + music.getId() + "/");
			musicService.updateById(music);
		}
		return true;
	}

	/**
	 * 批量上传伴奏
	 *
	 * @param files
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:51
	 */
	@Override
	public Boolean uploadBatchKala(List<MultipartFile> files, Integer collectionId) {

		Map<String, MisMusic> musicMap = MapUtil.newHashMap();

		//先校验 格式是否为 mp3
		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			if (!SUFFIX_MP3.equals(fileSuffix)) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_UPLOAD_MP3_FILE);
			}
			//根据文件名称查询曲目数据
			MisMusic music = musicService.getOne(new QueryWrapper<MisMusic>()
					.eq(MisMusic.COL_NAME, filedNameBefore)
					.and(x -> x.eq(MisMusic.COL_DEL_FLAG, "0"))
					.and(x -> x.eq(MisMusic.COL_COLLECTION_ID, collectionId)));
			//没查询到曲目信息则报错
			if (music == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_NON_MUSIC_FILE);
			}

//			if (!collectionId.equals(music.getCollectionId())) {
//				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_KALA_NOT_IN_COLLECTION);
//			}

			musicMap.put(music.getName(), music);
		}

		//遍历文件集合，只上传后缀名为 MP3 的文件
		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			//根据文件名称查询曲目数据
			MisMusic music = musicMap.get(filedNameBefore);

			//上传
			String ossKalaFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "_kala.mp3";

			try {
				//上传文件
				minioTemplate.uploadFile(file.getInputStream(), ossKalaFileName, BUCKET_KALA);
				//更新伴奏状态
				music.setKalaFile(CommonString.OSS_MUSIC_FILE + ossKalaFileName);
				music.setKalaStatus("1");
				musicService.updateById(music);
			} catch (IOException e) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, e.getLocalizedMessage());
			}
		}
		return true;
	}

	/**
	 * 音频批量上传
	 *
	 * @param files
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:54
	 */
	@Override
	public Boolean uploadBatchMP3(List<MultipartFile> files, Integer collectionId) {

		Map<String, MisMusic> musicMap = MapUtil.newHashMap();

		//先校验 格式是否为 mp3
		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			if (!SUFFIX_MP3.equals(fileSuffix)) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_UPLOAD_MP3_FILE);
			}

			//根据文件名称查询曲目数据
			MisMusic music = musicService.getOne(new QueryWrapper<MisMusic>()
					.eq(MisMusic.COL_NAME, filedNameBefore)
					.and(x -> x.eq(MisMusic.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL))
					.and(x -> x.eq(MisMusic.COL_COLLECTION_ID, collectionId)));

			//没查询到曲目信息则报错
			if (music == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_NON_MUSIC_FILE);
			}

//			if (!collectionId.equals(music.getCollectionId())) {
//				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_MUSIC_NOT_IN_COLLECTION);
//			}

			musicMap.put(music.getName(), music);

		}

		//遍历文件集合，只上传后缀名为 MP3 的文件
		for (MultipartFile file : files) {

			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			//根据文件名称查询曲目数据
			MisMusic music = musicMap.get(filedNameBefore);

			//上传
			String ossMp3FileName = collectionId + "/" + music.getId() + "/" + music.getId() + "_mp3.mp3";

			try {
				// 上传操作
				minioTemplate.uploadFile(file.getInputStream(), ossMp3FileName, BUCKET_MP3_MV);
				// 更新mp3路径
				music.setMp3File(CommonString.OSS_MUSIC_FILE + ossMp3FileName);
				musicService.updateById(music);
			} catch (IOException e) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, e.getLocalizedMessage());
			}
		}

		return true;
	}

	/**
	 * MV文件批量上传
	 *
	 * @param files
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:57
	 */
	@Override
	public String uploadBatchMv(List<MultipartFile> files, Integer collectionId) {

		Map<String, MisMusic> musicMap = MapUtil.newHashMap();

		//批次id
		String updateBatchId = "updateBatch_" + collectionId + "_" + System.currentTimeMillis();

		long start1 = System.currentTimeMillis();

		//校验mv文件
		for (MultipartFile file : files) {
			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			if (!Arrays.asList(mvFileType).contains(fileSuffix)) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_UPLOAD_MV_FILE);
			}

			//根据文件名称查询曲目数据
			MisMusic music = musicService.getOne(new QueryWrapper<MisMusic>()
					.eq(MisMusic.COL_NAME, filedNameBefore)
					.and(x -> x.eq(MisMusic.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL))
					.and(x -> x.eq(MisMusic.COL_COLLECTION_ID, collectionId)));

			//没查询到曲目信息则报错
			if (music == null) {
				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_NON_MUSIC_FILE);
			}

//			if (music.getCollectionId() != collectionId) {
//				throw new BusinessException(CommonConstants.FAIL_BOARD, MSG_MV_NOT_IN_COLLECTION);
//			}

			musicMap.put(music.getName(), music);
		}

		long end1 = System.currentTimeMillis();
		logger.info("consume1: " + (end1 - start1) + "ms");

		long start2 = System.currentTimeMillis();

//		files.parallelStream().forEach((file->{
		for (MultipartFile file : files) {
			//提取文件名
			String fileName = file.getOriginalFilename().replace(" ", "");
			//获取后缀名
			String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			//提取文件名（不含后缀）
			String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));

			//根据文件名称查询曲目数据
			MisMusic music = musicMap.get(filedNameBefore);

			//上传
			String ossMvFileName = collectionId + "/" + music.getId() + "/" + music.getId() + "_mv" + fileSuffix;

			try {
				//获取上传路径
//				String url = minioTemplate.uploadFile(file.getInputStream(), ossMvFileName, BUCKET_MP3_MV);

				Map<String, Object> cacheMap = new HashMap();
				cacheMap.put("updateBatchId", updateBatchId);
				cacheMap.put("music", music);
				cacheMap.put("ossMvFileName", ossMvFileName);

				redisTemplate.opsForValue().set(ossMvFileName, cacheMap, 600, TimeUnit.SECONDS);
				misMusicUploadService.uploadFileAsync(file.getBytes(), ossMvFileName, BUCKET_MP3_MV);
				redisTemplate.opsForValue().set(updateBatchId + ":" + music.getId(), 2, 600, TimeUnit.SECONDS);
			} catch (Exception e) {
				redisTemplate.opsForValue().set(updateBatchId + ":" + music.getId(), 0, 600, TimeUnit.SECONDS);
				throw new BusinessException(CommonConstants.FAIL_BOARD, e.getLocalizedMessage());
			}
		}
//		}));

		long end2 = System.currentTimeMillis();
		logger.info("consume2: " + (end2 - start2) + "ms");

		return updateBatchId;
	}

	/**
	 * 检查MV文件批量上传结果
	 *
	 * @param updateBatchId
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/4 17:57
	 */
	@Override
	public List<CheckUploadResultDTO> checkBatchMvResult(String updateBatchId, Integer collectionId) {
		List<CheckUploadResultDTO> resultList = new ArrayList<>();

		//根据文件名称查询曲目数据
		List<MisMusic> musicList = musicService.list(new QueryWrapper<MisMusic>()
				.eq(MisMusic.COL_COLLECTION_ID, collectionId)
				.and(x -> x.eq(MisMusic.COL_DEL_FLAG, CommonConstants.STATUS_NORMAL)));

		for (MisMusic music : musicList) {
			CheckUploadResultDTO singleResult = new CheckUploadResultDTO();
			String result = null;
			if (redisTemplate.opsForValue().get(updateBatchId + ":" + music.getId()) == null) {
				continue;
			} else if ((int) (redisTemplate.opsForValue().get(updateBatchId + ":" + music.getId())) == 1) {
				result = "上传成功";
			} else if ((int) (redisTemplate.opsForValue().get(updateBatchId + ":" + music.getId())) == 0) {
				result = "上传失败";
			} else if ((int) (redisTemplate.opsForValue().get(updateBatchId + ":" + music.getId())) == 2) {
				result = "上传中";
			} else {
				result = "未查到上传资源，请重新上传";
			}
			singleResult.setMusicName(music.getName());
			singleResult.setStatus(result);
			resultList.add(singleResult);
		}

		return resultList;
	}

	/**
	 * 校验文件名的一致性
	 *
	 * @param
	 * @return java.lang.String
	 * @author nianhua.jiang
	 * @date 2020/7/17 9:42
	 */
	private String checkFileName(List<MultipartFile> files) {

		String fileNameResult = StringUtils.EMPTY;

		if (files == null || files.size() == 0) {
			return fileNameResult;
		}

		Set<String> nameListSvg = files.stream()
				.filter(x -> SUFFIX_SVG.equals(x.getOriginalFilename().substring(x.getOriginalFilename().lastIndexOf(".") + 1)))
				.map(x -> x.getOriginalFilename().substring(0, x.getOriginalFilename().lastIndexOf(".") - 3))
				.collect(Collectors.toSet());

		Set<String> nameListXml = files.stream()
				.filter(x -> SUFFIX_XML.equals(x.getOriginalFilename().substring(x.getOriginalFilename().lastIndexOf(".") + 1)))
				.map(x -> x.getOriginalFilename().substring(0, x.getOriginalFilename().lastIndexOf(".")))
				.collect(Collectors.toSet());

		if (nameListSvg.equals(nameListXml)) {
			fileNameResult = nameListSvg.toString();
		}
		return fileNameResult;
	}

}
